﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ProtoBuf;

namespace GeneralDFS.DataEntity.IO
{
    /// <summary>
    /// 文件块的元数据
    /// </summary>
    [ProtoContract]
    [Serializable]
    public class FileBlockMetaData
    {
        /// <summary>
        /// 文件名
        /// </summary>
        [ProtoMember(1)]
        public String FileName { set; get; }

        /// <summary>
        /// 完整路径，包括文件名
        /// </summary>
        [ProtoMember(2)]
        public String FullPath { set; get; }

        /// <summary>
        /// 在文件中的偏移量
        /// </summary>
        [ProtoMember(3)]
        public long Offset { set; get; }

        /// <summary>
        /// 文件块的大小
        /// </summary>
        [ProtoMember(4)]
        public long Length { set; get; }

        /// <summary>
        /// 文件块的Hash值
        /// </summary>
        [ProtoMember(5)]
        public String Hash { set; get; }

        /// <summary>
        /// 唯一标识符，也是文件块的DataNode上的文件名
        /// </summary>
        [ProtoMember(6)]
        public Guid Guid { set; get; }

        [ProtoMember(7)]
        public bool IsSmallFile { set; get; }
        
        public virtual void WriteToBinary(BinaryWriter binaryWriter)
        {
            if (!binaryWriter.BaseStream.CanWrite) return;
            binaryWriter.Write(FileName);
            binaryWriter.Write(FullPath);
            binaryWriter.Write(Offset);
            binaryWriter.Write(Length);
            binaryWriter.Write(Hash);
            binaryWriter.Write(Guid.ToString());
            binaryWriter.Write(IsSmallFile);
        }

        public virtual FileBlockMetaData ReadFromBinary(BinaryReader binaryReader)
        {
            if (!binaryReader.BaseStream.CanRead) return null;
            FileName = binaryReader.ReadString();
            FullPath = binaryReader.ReadString();
            Offset = binaryReader.ReadInt64();
            Length = binaryReader.ReadInt64();
            Hash = binaryReader.ReadString();
            Guid=new Guid(binaryReader.ReadString());
            IsSmallFile = binaryReader.ReadBoolean();
            return this;
        }
    }
}